<template>
  <div class="comprehensive-analysis">
    <div ref="chartRef" class="chart-container"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, watch } from 'vue'
import * as echarts from 'echarts'

// 定义props
const props = defineProps({
  logList: {
    type: Array,
    default: () => []
  }
})

// 图表实例
const chartRef = ref(null)
let chartInstance = null

// 初始化图表
const initChart = () => {
  if (chartRef.value) {
    chartInstance = echarts.init(chartRef.value)
    updateChart()
  }
}

// 更新图表
const updateChart = () => {
  if (!chartInstance) return
  
  updateIndividualChart()
}

// 更新个人图表
const updateIndividualChart = () => {
  // 处理数据，按学生分组计算各维度分数
  const studentData = {}
  
  props.logList.forEach(item => {
    const key = `${item.studentNumber}-${item.studentName}`
    if (!studentData[key]) {
      studentData[key] = {
        studentNumber: item.studentNumber,
        studentName: item.studentName,
        scores: {0: 0, 1: 0, 2: 0, 3: 0, 4: 0} // 初始化各维度分数
      }
    }
    // 累加各维度分数
    studentData[key].scores[item.logType] += parseFloat(item.score) || 0
  })
  
  // 转换为图表需要的数据格式
  const indicator = [
    { name: '课程学习', max: 100 },
    { name: '学习时长', max: 100000 },
    { name: '竞赛情况', max: 1000 },
    { name: '项目实践', max: 100 },
    { name: '科创贡献', max: 1000 }
  ]
  
  const seriesData = []
  for (const key in studentData) {
    const student = studentData[key]
    seriesData.push({
      name: `${student.studentName}(${student.studentNumber})`,
      value: [
        student.scores[0],
        student.scores[1],
        student.scores[2],
        student.scores[3],
        student.scores[4]
      ]
    })
  }
  
  const option = {
    title: {
      text: '学生综合能力分析图'
    },
    tooltip: {
      trigger: 'item'
    },
    legend: {
      top: 'bottom'
    },
    radar: {
      indicator: indicator,
      radius: '60%'
    },
    series: [{
      type: 'radar',
      data: seriesData
    }]
  }
  
  chartInstance.setOption(option, true)
}

// 调整图表大小
const resizeChart = () => {
  if (chartInstance) {
    chartInstance.resize()
  }
}

// 暴露方法给父组件
defineExpose({
  resizeChart
})

// 组件挂载时初始化
onMounted(() => {
  initChart()
  window.addEventListener('resize', resizeChart)
})

// 组件卸载时清理
// onUnmounted(() => {
//   window.removeEventListener('resize', resizeChart)
//   if (chartInstance) {
//     chartInstance.dispose()
//   }
// })

// 监听数据变化，更新图表
watch(
  () => props.logList,
  () => {
    nextTick(() => {
      updateChart()
    })
  }
)
</script>

<style scoped>
.comprehensive-analysis {
  width: 100%;
  height: 100%;
}

.chart-container {
  width: 100%;
  height: 500px;
}
</style>